from decimal import Decimal
from django.shortcuts import render

# Create your views here.
from rest_framework.generics import GenericAPIView, CreateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

from carts.utils import ReadWriteTool
from goods.models import SKU
from orders.serializers import GetOrderSerializer, SkuSerializer, SaveOrderSerializer


class GetOrderView(GenericAPIView):
    # 请求方式 ： GET /orders/settlement/
    serializer_class = GetOrderSerializer
    permission_classes = [IsAuthenticated]

    def get(self, request):
        user = request.user
        # 从redis中获取购物车的信息
        tool = ReadWriteTool()
        carts_dict = tool.read_from_redis(user.id)
        # carts_dict = {'sku_id':[1,True],'sku_id2':[2,False]}
        skus = []
        for item in carts_dict.keys():
            if carts_dict[item][1]:
                sku = SKU.objects.get(id=item)
                sku_dict = {
                    'name': sku.name,
                    'default_image_url': sku.default_image_url,
                    'price': sku.price,
                    'count': carts_dict[item][0]
                }
                s = SkuSerializer(data=sku_dict)
                s.is_valid(raise_exception=True)
                skus.append(s.data)
        freight = Decimal('10.00')

        serializer = self.get_serializer({'freight': freight, 'skus': skus})
        return Response(serializer.data)


class SaveOrderView(CreateAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = SaveOrderSerializer
